import * as React from 'react';
import {Table, Form, Select, Input, Button, Col, Row, Modal, Icon, Popver, Steps, notification } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import axios from 'axios'
import Api from '../../services/apis'
import { func } from 'prop-types';

const FormItem = Form.Item;
const Option = Select.Option;
const Step = Steps.Step;

@connect (({user, loading}) => ({
    currentUser: user.currentUser,
    currentUserLoading: loading.effects['user/fetchCurrent']
}))

class RecordManagement extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            modalVisible: false,
            loading: true,
            canEdit: true,
            tableData: [],
            m_tableData: [],
            current: 1,
            pageSize: 5,
            m_current: 1,
            m_pageSize: 5,
            submitFlag : '',
            rooms:[],
            cabinets:[],
            boxs:[],
            docId: '',
        }
    }

    sendData = () => {
        const that = this;
        const searchValues = this.props.form.getFieldsValue();
        axios.post(Api.rmGetDocList,{
            docName: searchValues.s_name,
            docStatus: searchValues.s_state,
            docType: searchValues.s_type,
            currentPage: this.state.current
        })
        .then((function(resp){
            const data = resp.data;
            if(data.list.length === 0){
                notification.destroy();
                notification['warning']({message:'暂无数据'})
            }else{
                data.list.forEach((d,i) => {
                    d.key = i;
                    d.doc_status = d.doc_status === '0' ? "未借出" : parseInt(d.doc_status) < 4 ? '审批中' : "已借出";
                    switch (d.doc_type){
                        case "0":
                            d.doc_type = "核实情况报告";
                        break;
                        case "1":
                            d.doc_type = "内部文档";
                        break;
                        case "2":
                            d.doc_type = "划转通知";
                        break;
                        case "3":
                            d.doc_type = "权属文件";
                        break;
                    }

                });
            }

            that.setState({
                tableData: data.list,
                pageSize: data.pageSize,
                current: data.currentPage,
                totalSize: data.totalSize
            })
        }))
    }

    componentWillMount(){
        
        //请求数据
        this.sendData();

        //获取房间下拉
        this.getRoomList();
    }

    query = (e) => {
        e.preventDefault();
        /* this.props.form.validateFields((err,values)=>{
            if(!err){
                console.log('value:',values)
            }
        }) */
        this.setState({current:1},()=>{
            this.sendData();
        })
    }

    pageChange = (page) => {
        this.setState({current:page},()=>{
            this.sendData();
        })
    }

    resetForm = () => {
        this.props.form.resetFields();
    }

    setModalVisible = (visible) => {
        this.setState({modalVisible:visible})
    }
    
    //新建、修改开启模态框
    openModal = (type,id) => {
        const that = this;
        this.setState({submitFlag:type}); 
        if(type != 'add'){
            //根据ID查询档案信息
            axios.post(Api.rmGetDocById,{
                docId:id
            })
            .then(function(resp){
                 const data = resp.data;
                that.setModalVisible(true);
                const borrowedStatus = ['1','2','3','4'];
                const state = borrowedStatus.indexOf(data.doc_status) == -1 ? '0' : '1';
                that.props.form.setFieldsValue({
                    m_number: data.ref_code,
                    m_name: data.doc_name,
                    m_room: data.houseid,
                    m_type: data.doc_type,
                    m_state: state,
                })
                that.setState({docId:id, doc_status:data.doc_status});

                //根据房间获取柜下拉
                that.getPositionList('cabinets',data.houseid)
                .then(function(){
                    that.props.form.setFieldsValue({m_cabinet:data.cabinetid})
                    
                    //根据柜获取盒下拉
                    that.getPositionList('boxs',data.cabinetid)
                    .then(function(){
                        that.props.form.setFieldsValue({m_box:data.boxid})
                    })
                })

                that.getRecord(id);
            })
        }else{
            that.setModalVisible(true);
            this.props.form.setFieldsValue({
                m_number: "",
                m_name: "",
                m_location: "",
                m_room: "",
                m_type: "",
                m_state: "0",
                m_box:'',
                m_cabinet:''
            })
        }
    }

    //新建/修改
    modalSubmit = ()=> {
        const that = this;
        if(that.state.submitFlag == 'show'){
            that.setModalVisible(false);
            return;
        }

        that.props.form.validateFields((err,values)=>{
            if(!err){
                let url = ''
                let param = {
                    refCode: values.m_number,
                    docName: values.m_name,
                    packageId: values.m_box,
                    docStatus: values.m_state,
                    docType: values.m_type
                }
                if(this.state.submitFlag == "add"){//新增
                    url = Api.rmAddDoc;
                }else if(this.state.submitFlag == "edit"){//更新
                    url = Api.rmUpdateDoc;
                    param.docId = that.state.docId;
                    param.docStatus = param.docStatus == '1' ?  that.state.doc_status : param.docStatus;
                }
                axios.post(url,param)
                .then(function(resp){
                    const data = resp.data;
                    if(data.flag === '0'){
                        notification.destroy();
                        notification['warning']({message:data.msg});
                    }else if(data.flag === '1'){
                        notification.destroy();
                        notification['success']({message:data.msg});
                        that.sendData();
                    }
                    that.setModalVisible(false);
                })
            }
        })
    }

    //获取房间下拉
    getRoomList = () => {
        const that = this;
        axios.post(Api.rmGetPositionList,{})
        .then(function(resp){
            that.setState({
                rooms: resp.data
            })
        })
    }
    
    //根据房间获取柜子/根据柜子过去档案盒
    getPositionList = (type,value) => {
        const that = this;
        return axios.post(Api.rmGetPositionListByParentList,{
            parentId : value
        })
        .then(function(resp){
            if(type=="cabinets"){
                that.setState({
                    cabinets: resp.data
                })
                that.props.form.setFieldsValue({
                    m_cabinet: '',
                    m_box: '',
                })
            }else{
                that.setState({
                    boxs: resp.data
                })
                that.props.form.setFieldsValue({
                    m_box: '',
                })
            }
        })
    }

    //获取档案借款记录
    getRecord = (id) => {
        const that = this;
        axios.post(Api.rmGetRecord,{
            docId: id,
            currentPage: that.state.m_current
        })
        .then(function(resp){
            const { data } = resp;
            if(data.list && data.list.length !== 0){
                data.list.forEach((d,i) => {
                    d.key = i;
                    d.borrowdate = d.borrowdate.substring(0,10);
                });
            }

            that.setState({
                m_tableData: data.list,
                m_pageSize: data.pageSize,
                m_current: data.currentPage,
                m_totalSize: data.totalSize
            })
        })
    }

    m_pageChange = (page) => {
        this.setState({m_current:page},()=>{
            this.sendData(this.state.docId);
        })
    }

    render () {
        const that = this;
        const { form : { getFieldDecorator }, currentUserLoading } = this.props;

        const columns = [
            {
                title: '档案名称',
                key: 'doc_name',
                dataIndex: 'doc_name',
            },
            {
                title: '档案位置',
                key: 'cabinetdesc',
                dataIndex: 'cabinetdesc',
            },
            {
                title: '档案柜所在房间',
                key: 'housedesc',
                dataIndex: 'housedesc',
            },
            {
                title: '档案状态',
                key: 'doc_status',
                dataIndex: 'doc_status',
            },
            {
                title: '档案类型',
                key: 'doc_type',
                dataIndex: 'doc_type',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <span>
                    <a href="javascript:;" onClick={()=>this.openModal("show",record.doc_id)}>
                        详情
                    </a>
                    &emsp;
                    <a href="javascript:;" onClick={()=>this.openModal("edit",record.doc_id)}>
                        编辑
                    </a>
                    </span>
                ),
            },
        ]

        const m_columns = [
            {
                title: '借取人',
                key: 'borrowuser',
                dataIndex: 'borrowuser',
            },
            {
                title: '借取日期',
                key: 'borrowdate',
                dataIndex: 'borrowdate',
            },
            {
                title: '借取事由',
                key: 'borrowcause',
                dataIndex: 'borrowcause',
            },
            {
                title: '归还日期',
                key: 'returndate',
                dataIndex: 'returndate',
            },
            {
                title: '审批人',
                key: 'auditdeptname',
                dataIndex: 'auditdeptname',
            },
            {
                title: '经办人',
                key: 'chargedeptname',
                dataIndex: 'chargedeptname',
            },
            {
                title: '经办部门领导',
                key: 'chargepersonname',
                dataIndex: 'chargepersonname',
            }
        ]


        return (
            <PageHeaderWrapper loading={currentUserLoading}>
                <div className='mainContainer'>
                    <div className='contentHeader'>
                        <div className='contentHeaderTitle'>
                            <p>档案管理</p>
                            <p>RECORD MANAGEMENT</p>
                        </div>
                    </div>

                    <div className='pom'>
                        <div className='mrb15'>
                            <Form layout='inline' align='center' onSubmit={this.query}>
                                <FormItem label="档案名称：">
                                    {
                                        getFieldDecorator('s_name')(
                                            <Input placeholder="请输入档案名称"/>
                                        )
                                    }
                                </FormItem>
                                <FormItem label='档案状态：'>
                                    {
                                        getFieldDecorator('s_state')(
                                            <Select placeholder="请选择档案状态">
                                                <Option value="0">未借出</Option>
                                                <Option value="1">已借出</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                                <FormItem label='档案类型：'>
                                    {
                                        getFieldDecorator('s_type')(
                                            <Select placeholder="请选择档案类型">
                                                <Option value="0">核实情况报告</Option>
                                                <Option value="1">内部文档</Option>
                                                <Option value="2">划转通知</Option>
                                                <Option value="3">权属文件</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                                <Row gutter={24} style={{ textAlign: 'center'}}>
                                    <Button icon='search' type='primary' htmlType='submit'>搜索</Button>&emsp;
                                    <Button icon="plus-circle" type="primary" htmlType='button' onClick={()=>this.openModal("add")}>新建</Button>&emsp;
                                    <Button icon="reload" type="primary" htmlType='button' onClick={this.resetForm}>重置</Button>
                                </Row>
                            </Form>
                        </div>

                        <Table 
                            bordered={true}
                            scroll={{ x:true }}
                            columns={columns}
                            dataSource={this.state.tableData}
                            pagination={{
                              defaultPageSize: that.state.pageSize,
                              current: that.state.current,
                              onChange: that.pageChange,
                              total: that.state.totalSize,
                              showTotal: total => `共 ${total} 项`
                            }}/>
                    </div>

                    <Modal
                        title={this.state.submitFlag == 'show' ? '档案详情' : (this.state.submitFlag == 'add' ? '新增档案' : '编辑档案')}
                        centered
                        visible={this.state.modalVisible}
                        onOk={this.modalSubmit}
                        onCancel={()=>this.setModalVisible(false)}
                        width={830}
                        className='oaomodal'
                    >
                        <Row gutter={24}>
                            <Col span={8}>
                                <FormItem label='档案编号：'>
                                    {getFieldDecorator('m_number',{
                                        rules:[{required:true,message:'请输入档案编号！'}]
                                    })(<Input placeholder="请输入档案编号" disabled={this.state.submitFlag == 'show' ? true : false}/>)}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='档案名称：'>
                                    {getFieldDecorator('m_name',{
                                        rules:[{required:true,message:'请输入档案名称！'}]
                                    })(<Input placeholder="请输入档案名称" disabled={this.state.submitFlag == 'show' ? true : false}/>)}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='所在房间：'>
                                    {getFieldDecorator('m_room',{
                                        rules:[{required:true,message:'请选择所在房间！'}]
                                    })(<Select style={{width:"100%"}} placeholder="请选择所在房间" onChange={(value)=>this.getPositionList("cabinets",value)} disabled={this.state.submitFlag == 'show' ? true : false}>
                                        {this.state.rooms.map((item,index)=>
                                            <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                                        )}
                                    </Select>)}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='所在档案柜：'>
                                    {getFieldDecorator('m_cabinet',{
                                        rules:[{required:true,message:'请选择所在档案柜！'}]
                                    })(<Select style={{width:"100%"}}placeholder="请选择所在档案柜" onChange={(value)=>this.getPositionList('boxs',value)} disabled={this.state.submitFlag == 'show' ? true : false}>
                                        {this.state.cabinets.map((item,index)=>
                                            <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                                        )}
                                    </Select>)}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='所在档案盒：'>
                                    {getFieldDecorator('m_box',{
                                        rules:[{required:true,message:'请选择所在档案盒！'}]
                                    })(<Select style={{width:"100%"}}placeholder="请选择所档案盒" disabled={this.state.submitFlag == 'show' ? true : false}>
                                        {this.state.boxs.map((item,index)=>
                                            <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                                        )}
                                    </Select>)}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='档案类型：'>
                                    {getFieldDecorator('m_type',{
                                        rules:[{required:true,message:'请输入档案类型！'}]
                                    })(
                                        <Select style={{width:'100%'}} placeholder="请选择档案类型" disabled={this.state.submitFlag == 'show' ? true : false}>
                                            <Option value="0">核实情况报告</Option>
                                            <Option value="1">内部文档</Option>
                                            <Option value="2">划转通知</Option>
                                            <Option value="3">权属文件</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='档案状态：'>
                                    {getFieldDecorator('m_state',{
                                        rules:[{required:true,message:'请输入档案状态！'}]
                                    })(
                                        <Select style={{width:'100%'}} placeholder="请选择档案状态" disabled={this.state.submitFlag == 'show' ? true : false}>
                                            <Option value="0">未借出</Option>
                                            <Option value="1">已借出</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <div style={{display:this.state.submitFlag == 'show'?'block':'none'}}>
                            档案借款记录：
                            <Table
                                border={true}
                                columns={m_columns}
                                size={'small'}
                                dataSource={this.state.m_tableData}
                                pagination={{
                                  defaultPageSize: that.state.m_pageSize,
                                  current: that.state.m_current,
                                  onChange: that.m_pageChange,
                                  total: that.state.m_totalSize,
                                  showTotal: total => `共 ${total} 项`
                                }}/>
                        </div>
                    </Modal>
                </div>
            </PageHeaderWrapper>
        )
    }
}

const WrappedApp = Form.create()(RecordManagement);

export default WrappedApp;
